package com.congiya.map;

import java.io.IOException;
import java.util.HashMap;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.congiya.struts2.FrontActionSupport;
import com.congiya.weather.KmaRssChannelVO;
import com.congiya.weather.KmaRssDataVO;
import com.congiya.weather.KmaRssDescriptionVO;
import com.congiya.weather.KmaRssItemVO;
import com.congiya.weather.KmaRssVO;
import com.congiya.weather.WeatherRegionBO;
import com.congiya.weather.WeatherRegionListVO;
import com.congiya.weather.WeatherRegionVO;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

public class SearchMapAction extends FrontActionSupport {

	private final Log logger = LogFactory.getLog(getClass());
    /**
	 * 
	 */

	
	private WeatherRegionBO wrBO;
	
	
    public void setWrBO(WeatherRegionBO wrBO) {
		this.wrBO = wrBO;
	}

    public String weatherByRegionNameToXML() throws HttpException, IOException {
    	
		WeatherRegionVO wrVO 				= null;		
		KmaRssVO kmaVO = null;
		
    	HashMap map 						= null;
    	String resStrXml 						= null;
    	
    	HttpClient client 					= null;
    	PostMethod method 					= null;
    	
    	XStream kmaXstream = null;
    	XStream resXstream = null;
    	
    	// Request 
    	String regionName 					= req.getParameter("regionName");    	
    	String searchWeatherURL				= "http://www.kma.go.kr/wid/queryDFSRSS.jsp";
    	
    	logger.debug("regionName : " + regionName);
    	map = new HashMap();
    	map.put("r1.name", regionName);
    	
    	//---------------------------------------------------------------------
    	// 날씨코드 조회 - DB
    	//---------------------------------------------------------------------
    	wrVO = wrBO.getWeatherRegionVO(map);
    	
    	if(wrVO == null || wrVO.getId() == null) {
    		
    		// error Msg
    	}
    	
    	logger.debug("regionId : " + wrVO.getId());
  
    	
    	//---------------------------------------------------------------------
    	// 기상청으로 날씨 정보 요청
    	//---------------------------------------------------------------------
		client = new HttpClient();
	    method = new PostMethod (searchWeatherURL);
        method.addRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        method.addParameter(new NameValuePair("zone", wrVO.getId()));	            
	    client.setTimeout(6000);
        client.executeMethod(method);
        
        // 기상청 날씨 정보 파싱
        kmaXstream = new XStream(new DomDriver());
    	initKmaAlias(kmaXstream);
    	kmaVO = (KmaRssVO) kmaXstream.fromXML(method.getResponseBodyAsStream());   
    	
/*    	
    	logger.debug("kmaVO : " + kmaVO);
    	
    	if(kmaVO != null && kmaVO.getChannel().getItem().getDescription().getBody() != null) {    		
    		
    		for(KmaRssDataVO kmaDataVO : kmaVO.getChannel().getItem().getDescription().getBody()) {
	    		logger.debug(
	    				"kmaDataVO.hour : " + kmaDataVO.getHour() +
	    				", kmaDataVO.day : " + kmaDataVO.getDay() +
	    				", kmaDataVO.temp : " + kmaDataVO.getTemp() +
	    				", kmaDataVO.sky : " + kmaDataVO.getSky() +
	    				", kmaDataVO.pty : " + kmaDataVO.getPty() +
	    				", kmaDataVO.wfKor : " + kmaDataVO.getWfKor()
	    		);
    		}
    	}
*/    	
    	
    	// 기상청 날씨정보 전달
    	resXstream = new XStream(new DomDriver());
    	initKmaAlias(resXstream);
    	
    	resStrXml = resXstream.toXML(kmaVO.getChannel().getItem().getDescription());
    	logger.debug("resStrXml : " + resStrXml);
    	    	
    	return null;
    }

	public String regionId() throws HttpException, IOException {
		
		WeatherRegionVO wrVO = null;
		
		WeatherRegionListVO wrListVO = new WeatherRegionListVO();
		WeatherRegionListVO resWrListVO = null;
		
    	HashMap map = new HashMap();    	    	
    	String regionName = req.getParameter("regionName");
    	String strXml = null;
    	
    	logger.debug("regionName : " + regionName);
    	map.put("r1.name", regionName);
    	
    	
    	// 주간날씨
    	//http://www.kma.go.kr/weather/forecast/mid-term-xml.jsp?stnId=108
    		
    	// 오늘날씨
    	//http://www.kma.go.kr/wid/queryDFSRSS.jsp?zone=1159068000
    	//3, 6, 9, 12, 15, 18,
    	
/*    	
    	- <data seq="5">
    	  <hour>12</hour>  : 시간
    	  <day>1</day>  : 현재를 기준으로 + 일
    	  <temp>26.7</temp>  : 현재기온
    	  <tmx>29.6</tmx>  : 최고기온
    	  <tmn>20.8</tmn> : 최저기온
    	  <sky>4</sky> : 하늘상태코드 (맑음1, 구름조금2, 구름많음3, 흐림4)
    	  <pty>0</pty>  : 강수상태코드 (없음0, 비1, 비/눈2, 눈3)
    	  <wfKor>흐림</wfKor> : 날씨
    	  <wfEn>Cloudy</wfEn>  : 날씨
    	  <pop>30</pop>  : 강수확률 %
    	  <r12>2.6862612</r12> : 12시간 예상강수량
    	  <s12>0.0</s12>  : 12시간 예상적설량
    	  <ws>1.3</ws> 풍속
    	  <wd>6</wd> 풍향코드
    	  <wdKor>서</wdKor> 풍향
    	  <wdEn>W</wdEn> 풍향:
    	  <reh>74</reh> : 습도%
    	  </data>
*/    	

    	wrVO = wrBO.getWeatherRegionVO(map);
    	
    	if(wrVO != null && wrVO.getId() != null) {
    		
    		wrListVO.add(wrVO);
    		logger.debug("stnId : " + wrVO.getStnId());
    	}
    	
    	
    	XStream xstream = new XStream(new DomDriver());
    	initAlias(xstream);
    	strXml = xstream.toXML(wrListVO);
    	logger.debug("strXml : " + strXml);
    	
    	resWrListVO = (WeatherRegionListVO)xstream.fromXML(strXml);
    	logger.debug("resWrListVO : " + resWrListVO);
    	
    	if(resWrListVO != null) {
    		
    		for(WeatherRegionVO resWrVO : resWrListVO.getDescription()) {
	    		logger.debug(
	    				"resWrVO.id : " + resWrVO.getId() +
	    				", resWrVO.name : " + resWrVO.getName() +
	    				", resWrVO.code : " + resWrVO.getParentCode()
	    		);
    		}
    	}
    	
    	//req.setAttribute("wrVO", wrVO);
    	
		HttpClient client = new HttpClient();
	    PostMethod method = new PostMethod ( "http://www.kma.go.kr/wid/queryDFSRSS.jsp" );
        method.addRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        method.addParameter(new NameValuePair("zone", wrVO.getId()));	    
        
	    client.setTimeout(6000);
        client.executeMethod(method);
                
	    
    	XStream xstream2 = new XStream(new DomDriver());
    	initKmaAlias(xstream2);
    	KmaRssVO kmaVO = (KmaRssVO) xstream2.fromXML(method.getResponseBodyAsStream());
    	
    	logger.debug("kmaVO : " + kmaVO);
    	
    	if(kmaVO != null) {
    		
    		logger.debug("kmaVO : " + kmaVO.getChannel().getItem().getDescription().getHeader().getTm());
    		logger.debug("kmaVO : " + kmaVO.getChannel().getItem().getDescription().getBody());
    		
    		for(KmaRssDataVO kmaDataVO : kmaVO.getChannel().getItem().getDescription().getBody()) {
	    		logger.debug(
	    				"kmaDataVO.hour : " + kmaDataVO.getHour() +
	    				", kmaDataVO.day : " + kmaDataVO.getDay() +
	    				", kmaDataVO.temp : " + kmaDataVO.getTemp() +
	    				", kmaDataVO.sky : " + kmaDataVO.getSky() +
	    				", kmaDataVO.pty : " + kmaDataVO.getPty() +
	    				", kmaDataVO.wfKor : " + kmaDataVO.getWfKor()
	    		);
    		}
    	}
    	
    	
    	return null;
    }

	public void initAlias(XStream xstream) {
	    xstream.alias("item", WeatherRegionListVO.class);
	    xstream.alias("data", WeatherRegionVO.class);
	}

	public void initKmaAlias(XStream xstream) {
		xstream.alias("rss", KmaRssVO.class);
		xstream.alias("channel", KmaRssChannelVO.class);
		xstream.alias("description", KmaRssDescriptionVO.class);
	    xstream.alias("item", KmaRssItemVO.class);
	    xstream.alias("data", KmaRssDataVO.class);
	}	
	
	public void initResAlias(XStream xstream) {
		xstream.alias("description", KmaRssDescriptionVO.class);
	    xstream.alias("data", KmaRssDataVO.class);
	}	
	
	
    //private OrdersService ordersService = new OrdersService();
}
